package com.cosina.game.crystallight.engine;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

import com.cosina.game.crystallight.MediaPlayerAdapter;
import com.cosina.game.crystallight.engine.util.FPS;
import com.cosina.game.crystallight.engine.util.Time;
import com.cosina.game.crystallight.model.enemy.Enemy;

public class EnemyManager implements Time{
	public final LinkedList<Enemy> enemies = new LinkedList<Enemy>();
	public final int[][] waveKind;
	public EnemyManager() {
		waveKind = BattleEngine.field.waveKind();
		Enemy.direction = BattleEngine.field.pathDirection();
	}

	public boolean noEnemy(){
		return enemies.size() == 0;
	}
	
	private boolean hasAnyEnemyKilled = false;
	@Override
	public void withTimeGo() {
		if(noEnemy() && hasAnyEnemyKilled){
			BattleEngine.wavePanelManager.knockDoor();
			return;
		}
		
		Iterator<Enemy> iter = enemies.iterator();
		
		while(iter.hasNext()){
			Enemy enemy = iter.next();
			if(enemy.isDead()){
				BattleEngine.psManager.createExplosion(enemy.center);
				BattleEngine.manaFlask.absorb(enemy);
				BattleEngine.statistics.enemyKilled ++;
				BattleEngine.statistics.battleScoreNeedAddValue += enemy.totalHp;
				iter.remove();
				hasAnyEnemyKilled = true;
				continue;
			}
			enemy.withTimeGo();
			if(enemy.isWin()){
				MediaPlayerAdapter.hpDown();
				BattleEngine.sheild.hit(enemy.attack);
				enemy.initToStart();
			}
		}
		Collections.sort(enemies);
	}
	
	
	public void newWaveGo(int waveIndex){
		int kind = waveKind[waveIndex][0];
		int count = waveKind[waveIndex][1];
		
		for(int i=0; i<count; i++){
			if(waveKind[waveIndex].length == 2){
				Enemy enemy = new Enemy(kind, BattleEngine.field,20,20,20);
				enemy.wait = FPS.VALUE /3 * 2 * i;
				enemies.add(enemy);
			}else{
				Enemy enemy = new Enemy(kind, BattleEngine.field,waveKind[waveIndex][2],waveKind[waveIndex][3],waveKind[waveIndex][4]);
				enemy.wait = FPS.VALUE /3 * 2 * i;
				enemies.add(enemy);
			}
		}
	}
}
